package models

import (
	"time"

	"gorm.io/gorm"
)

type Partner struct {
	ID          uint           `json:"id" gorm:"primaryKey"`
	Name        string         `json:"name" gorm:"size:100;not null" binding:"required"`
	Type        string         `json:"type" gorm:"size:50;not null" binding:"required"`
	City        string         `json:"city" gorm:"size:50;not null" binding:"required"`
	Subjects    string         `json:"subjects" gorm:"type:text;not null" binding:"required"`
	Contact     string         `json:"contact" gorm:"size:50"`
	Phone       string         `json:"phone" gorm:"size:20"`
	Email       string         `json:"email" gorm:"size:100"`
	Address     string         `json:"address" gorm:"type:text"`
	WebhookURL  string         `json:"webhook_url" gorm:"size:255"`
	APIKey      string         `json:"api_key" gorm:"size:100"`
	Priority    int            `json:"priority" gorm:"default:1"`
	Status      string         `json:"status" gorm:"type:enum('active','inactive','suspended');default:'active'"`
	Description string         `json:"description" gorm:"type:text"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	PushRecords []PushRecord `json:"push_records" gorm:"foreignKey:PartnerID"`
}

// TableName 指定表名
func (Partner) TableName() string {
	return "partners"
}

// BeforeCreate 创建前钩子
func (p *Partner) BeforeCreate(tx *gorm.DB) error {
	if p.Status == "" {
		p.Status = "active"
	}
	if p.Priority == 0 {
		p.Priority = 1
	}
	return nil
}

// GetStatusText 获取状态文本
func (p *Partner) GetStatusText() string {
	statusMap := map[string]string{
		"active":    "正常",
		"inactive":  "停用",
		"suspended": "暂停",
	}
	if text, ok := statusMap[p.Status]; ok {
		return text
	}
	return "未知状态"
}

// IsActive 检查是否激活
func (p *Partner) IsActive() bool {
	return p.Status == "active"
}

// CanReceivePush 检查是否可以接收推送
func (p *Partner) CanReceivePush() bool {
	return p.IsActive() && p.WebhookURL != ""
}

// GetSubjectList 获取科目列表
func (p *Partner) GetSubjectList() []string {
	if p.Subjects == "" {
		return []string{}
	}
	// 假设科目用逗号分隔
	subjects := []string{}
	for _, subject := range []string{p.Subjects} {
		if subject != "" {
			subjects = append(subjects, subject)
		}
	}
	return subjects
}

// SupportsSubject 检查是否支持指定科目
func (p *Partner) SupportsSubject(subject string) bool {
	subjects := p.GetSubjectList()
	for _, s := range subjects {
		if s == subject {
			return true
		}
	}
	return false
}

// UpdateStatus 更新状态
func (p *Partner) UpdateStatus(db *gorm.DB, status string) error {
	p.Status = status
	return db.Save(p).Error
}